import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class GenerateSecretKeyExample {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        // 生成一个HmacSHA256密钥（256位）
        SecretKey secretKey = generateSecretKey("HmacSHA256", 256);

        // 将密钥转换为Base64编码字符串
        String base64Key = convertKeyToBase64(secretKey);

        System.out.println("Generated Secret Key: " + base64Key);
    }

    private static SecretKey generateSecretKey(String algorithm, int keySize) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
        keyGenerator.init(keySize);
        return keyGenerator.generateKey();
    }

    private static String convertKeyToBase64(SecretKey key) {
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }
}